package com.yinpeng.controller;

import com.yinpeng.entity.User;
import com.yinpeng.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@RequestMapping("/home")
public class HomeController {

    // logger
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    // userService
    @Autowired
    private UserService userService;

    // index action
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {
        //logs debug message
        if (logger.isDebugEnabled()) {
            logger.debug("getWelcome is executed!");
        }

        //logs exception
        logger.error("This is Error message", new Exception("Testing"));

        //返回一个index.jsp这个视图
        ModelAndView view = new ModelAndView("index");
        view.addObject("content", "this is index content.");
        return view;
    }

    // get users
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list() {
        List<User> ls = userService.getList();
        logger.info("users lists [{}]", ls);

        ModelAndView view = new ModelAndView("user_list");
        view.addObject("userData",ls);
        view.addObject("title","用户列表页");
        return view;
    }

    // 返回String(含中文)
    @RequestMapping(value = "/ret-string", method = RequestMethod.GET,produces = "text/plain; charset=utf-8")
    public String retString() {
        return "this is string. 你好!";
    }
}
